import { 
  BoxGeometry,
  CubeReflectionMapping,
  CubeRefractionMapping,
  CubeTextureLoader,
  Mesh,
  MeshStandardMaterial,
  PerspectiveCamera,
  Scene, 
  SphereGeometry, 
  TextureLoader, 
  WebGLRenderer
} from "three";
import stats from '../../utils/stats';
// 调用
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { GUI } from 'dat.gui';

let scene = new Scene();
let renderer = setRenderer();
let camera = setCamera();

let { cube, sphere } = init();
addGUI(scene);

const trackballControls = new OrbitControls(camera, renderer.domElement);
// 调整场景位置
trackballControls.target.set(0, 3, 0);

function render() {
  stats.update();
  trackballControls.update();

  cube.rotation.y += 0.01;
  sphere.rotation.y += 0.01;

  requestAnimationFrame(render);
  renderer.render(scene, camera);
}
render();

function setRenderer() {
  const renderer = new WebGLRenderer({ antialias: true });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  // 支持阴影生成 
  renderer.shadowMap.enabled = true;
  document.body.appendChild(renderer.domElement);

  return renderer
}

function setCamera(): PerspectiveCamera {
  let camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000);
  camera.position.set(0, 20, 40);
  scene.add( camera );

  return camera;
}

/** 功能区 */
function init() {
  let textureLoader = new TextureLoader();

  // 将全景图生成6张图工具
  // https://jaxry.github.io/panorama-to-cubemap/
  // https://360toolkit.co/convert-spherical-equirectangular-to-cubemap
  let urls = [
    '/textures/cubemap/flowers/right.png',
    '/textures/cubemap/flowers/left.png',
    '/textures/cubemap/flowers/top.png',
    '/textures/cubemap/flowers/bottom.png',
    '/textures/cubemap/flowers/front.png',
    '/textures/cubemap/flowers/back.png',
  ];
  let cubeLoader = new CubeTextureLoader();
  scene.background = cubeLoader.load(urls);

  let cubeMaterial = new MeshStandardMaterial({
    envMap: scene.background,
    color: 0xffffff,
    metalness: 1,
    roughness: 0
  });
  let cubeGeom = new BoxGeometry(16, 12, 12);
  let cube = new Mesh(cubeGeom, cubeMaterial);
  cube.position.x = -15;
  scene.add(cube);

  let sphereMater = cubeMaterial.clone();
  sphereMater.normalMap = textureLoader.load('/textures/engraved/Engraved_Metal_003_NORM.jpg');
  sphereMater.aoMap = textureLoader.load('/textures/engraved/Engraved_Metal_003_OCC.jpg');

  let sphereGeom = new SphereGeometry(10, 50, 50);
  let sphere = new Mesh(sphereGeom, sphereMater);
  sphere.position.x = 15;
  scene.add(sphere);

  return {cube, sphere}
}


function addGUI(scene: any): void {
  const gui = new GUI();  

  gui.add({refraction: false}, 'refraction').name('玻璃化').onChange(val => {
    if (val) {
      scene.background.mapping = CubeRefractionMapping;
    } else {
      scene.background.mapping = CubeReflectionMapping;
    }

    cube.material.needsUpdate = true;
    sphere.material.needsUpdate = true;
  })
}